﻿using AutoMapper;
using B.S.Orders.Domain;
using B.S.Procurement.Domain;
using B.S.Procurement.Error;
using B.S.Procurement.Read.Api.Application.Command.ProcurementCommand;
using B.S.Procurement.Read.Api.DTO;
using MediatR;
using SqlSugar;

namespace B.S.Procurement.Read.Api.Application.CommandHander.ProcurementCommandHander
{
    public class QueryProcurementCommandHander : IRequestHandler<QueryProcurementCommand, ApiPaging<List<ProcurementDto>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public QueryProcurementCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public Task<ApiPaging<List<ProcurementDto>>> Handle(QueryProcurementCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<List<ProcurementDto>> result = new ApiPaging<List<ProcurementDto>>();

            var item = db.Queryable<ProcurementModel>()
                       .InnerJoin<Purchase>((a, b) => a.PurchaseId == b.PurchaseId)
                       .InnerJoin<ProjectModel>((a, b, c) => a.ProjectId == c.ProjectId)
                       .Where((a, b, c) => a.Del == false)
                       .Select((a, b, c) => new ProcurementDto
                       {
                           ProcurementId = a.ProcurementId,
                           ProcurementTopics = a.ProcurementTopics,
                           PurchaseNumber = a.PurchaseNumber,
                           PurchaseType = a.PurchaseType,
                           PurchaseId = a.PurchaseId,
                           Time = a.Time,
                           personnel = a.personnel,
                           ProjectId = a.ProjectId,
                           Remark = a.Remark,
                           Del = a.Del,

                           PurchaseName = b.PurchaseName,

                           ProjectName = c.ProjectName,
                           ProjectNum = c.ProjectNum,
                           ProjectTime = c.ProjectTime,
                           ProjectPeople = c.ProjectPeople,
                           ProjectTypeId = c.ProjectTypeId,
                       });

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(a => a.ProcurementId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            result.Code = ApiEnum.success;
            result.Msg = "查询成功";
            result.Data = mapper.Map<List<ProcurementDto>>(item.ToList());

            return Task.FromResult(result);
        }
    }
}
